<template>
  <div class="date-picker">
    <div class="date" @click="yearMonthPopupVisible = true">
      <span>{{ yearMonthDisplayValue }}</span>
      <span class="triangle-down"></span>
    </div>

    <van-popup
      v-model="yearMonthPopupVisible"
      position="bottom"
      :lock-scroll="true"
    >
      <van-datetime-picker
        type="year-month"
        v-model="yearMonthComponentValue"
        :title="placeholder"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="yearMonthPopupVisible = false"
        @confirm="onYearMonthConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import nus from "@nsrd/nus";

export default {
  name: "DatePicker",
  props: {
    placeholder: String,
    value: String,
    // date
    maxDate: {
      type: Date,
      default: () => new Date()
    },
    minDate: {
      type: Date,
      default: () => new Date(1900, 0, 1)
    },
    defaultDate: {
      type: Date,
      default: () => new Date()
    }
  },
  watch: {
    value: {
      handler: function(val) {
        this.currentValue = val;
        this.yearMonthComponentValue = new Date(
          nus.date.format(val, "YYYYMM", "YYYY-MM")
        );
        this.yearMonthDisplayValue = nus.date.format(val, "YYYY-MM");
      },
      immediate: true
    },
    currentValue: {
      handler: function(value) {
        this.$emit("input", value);
      },
      immediate: true
    }
  },
  data() {
    return {
      currentValue: this.value,
      yearMonthDisplayValue: "", // 展示值
      yearMonthComponentValue: this.defaultDate,
      yearMonthPopupVisible: false
    };
  },
  mounted() {
    this.yearMonthComponentValue = new Date(
      nus.date.format(this.value, "YYYYMM", "YYYY-MM")
    );
  },
  methods: {
    onYearMonthConfirm(val) {
      this.currentValue = nus.date.format(val, "YYYYMM");
      this.yearMonthPopupVisible = false;
    }
  }
};
</script>

<style scoped lang="less">
.date-picker {
  .date {
    padding: 5px 10px;
    background: #edf0ff;
    border-radius: 4px;
    display: inline-block;
    margin-bottom: 10px;

    span {
      font-size: 14px;
      font-weight: 600;
      color: #333333;
    }

    .triangle-down {
      display: inline-block;
      vertical-align: middle;
      width: 0;
      height: 0;
      margin-left: 5px;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-top: 4px solid #333333;
    }
  }
}
</style>
